package com.godme.concurrent.juc;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.StampedLock;

public class StampedLockTest {

    static class Queue {
        private final StampedLock lock = new StampedLock() ;
        private final int[] arr;

        public Queue(int size){
            arr = new int[size];
        }


        public void put(int index, int data){
            long stamp = lock.writeLock();
            arr[index] = data;
            try{
                Thread.sleep(100);
            }catch (Exception e){
                e.printStackTrace();
            }
            lock.unlockWrite(stamp);
        }

        public int get(int index){
            long stamp = lock.tryOptimisticRead();
            int data = arr[index];
            if(!lock.validate(stamp)){
                stamp = lock.readLock();
                data = arr[index];
                lock.unlockRead(stamp);
            }
            return data;
        }
    }


    public static void main(String[] args) {
        Queue queue = new Queue(10);
        new Thread(()->{
            for (int i = 0; i < 10000; i++) {
                queue.put(i % 10, i);
            }
        }).start();

        AtomicInteger index = new AtomicInteger(0);
        new Thread(()->{
            while (true){
                System.err.println(queue.get(index.getAndIncrement() % 10));
            }
        }).start();
    }
}
